const { decodeGPS } = require('../../../utils/decodeGPS.js')
const { CurrencyShopModel } = require('../../../utils/currencyshop-model.js')
const { getDistance } = require('../../../utils/util.js')
const currencyShopModel = new CurrencyShopModel()
const { globalData } = getApp()
const { SvipModel } = require('../../../utils/svip-model.js')
var svipModel = new SvipModel()
const { Config } = require('../../../utils/config.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: globalData.isIphoneX,
    swiperImages: [
      'https://oss.kiscloud.net/wechat/images/swiper1.png',
      'https://oss.kiscloud.net/wechat/images/swiper2.png',
      'https://oss.kiscloud.net/wechat/images/swiper3.png',
      'https://oss.kiscloud.net/wechat/images/swiper4.png'
    ],
    shops: [],
    city: '定位中',
    cityCode: '',
    detailAddr: '定位中...',
    GPScity: '',
    GPScityCode: '',
    selectCity: null,
    selectShopId: '',
    sVipType: null,
    from: '',
    canSelectShopIds: [],
    shopId: "",
    activeIdx: 0
  },

  goCurrencyShop (e) {
    wx.reportAnalytics('currency_shop')
    const { address, shopName, shopId, cityCode, cityName } = e.currentTarget.dataset.shop
    // this.setData({ shopId: shopId }, function () {
    //   if (this.data.sVipType) {
    //     this.getMemberInfo();
    //   } else {
    //     wx.navigateTo({
    //       url: `/pages/currencyShop/chooseCurrency/index?shopName=${shopName}&address=${address || ''}&shopId=${shopId}`
    //     })
    //   }
    // })
    this.setData({
      activeIdx: e.currentTarget.dataset.index
    })
    wx.login({
      success: ({ code }) => {
        currencyShopModel.setUserSelectShop({
          shopId,
          code,
          appId: Config.appId,
          merchantId: wx.getStorageSync('merchantId') //商户id
        }).then(res => {
          // wx.setStorageSync('dontExchangeShop', true)
          if (this.data.from === 'activity') {
            wx.navigateBack()
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]
            prevPage.setData({
              cityCode,
              cityName,
              shopId,
              shopName
            })
            prevPage.calcBeans && prevPage.calcBeans()
          } else if (this.data.from === 'home') {
            wx.redirectTo({
              url: '/pages/index/index'
            })
          } else if (this.data.sVipType) {
            wx.navigateTo({
              url: `/pages/svip/purchase/index?shopId=${shopId}`
            })
          } else {
            wx.navigateBack()
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]
            prevPage.getShopInfo && prevPage.getShopInfo()
          }
        }).catch(err => {
          wx.showToast({
            title: '选择门店失败',
            icon: 'none',
            duration: 2000
          })
        })
      }
    })
  },
  goChooseCity () {
    wx.reportAnalytics('currency_city')
    wx.navigateTo({
      url: `/pages/chooseCity/index?city=${this.data.GPScity}&cityCode=${this.data.GPScityCode}`
    })
  },
  refreshAddr() {
    const selectCity = this.data.selectCity
    this.setData({
      detailAddr: '定位中...'
    })
    decodeGPS().then(res => {
      const { addressComponent, formatted_address, cityCode, location } = res
      this.setData({
        detailAddr: formatted_address,
        GPScity: addressComponent.city.replace('市', ''),
        GPScityCode: cityCode,
        lat: location.lat,
        lng: location.lng
      })
      if (!selectCity) {
        this.setData({
          city: addressComponent.city.replace('市', ''),
          cityCode,
          selectCity: {
            name: addressComponent.city.replace('市', ''),
            code: cityCode
          }
        })
        this.getShop(cityCode)
      } else {
        this.setData({
          city: selectCity.name,
          cityCode: selectCity.code
        })
        this.getShop(selectCity.code)
      }
    }).catch(err => {
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userLocation']) {
            wx.showToast({
              title: '定位失败',
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showModal({
              title: '提示',
              content: '没有授权定位信息，打开设置',
              success(res) {
                if (res.confirm) {
                  wx.openSetting()
                }
              }
            })
          }
        }
      })
    })
  },

  getLocation () {
    // const selectCity = this.data.selectCity
    // if (selectCity) {
    //   this.setData({
    //     city: selectCity.name,
    //     cityCode: selectCity.code
    //   })
    //   this.getShop(selectCity.code)
    // }
    this.refreshAddr()
  },
  getShop(cityCode) {
    const merchantId = wx.getStorageSync('merchantId')
    if (cityCode && cityCode !== 'undefined') {
      currencyShopModel.getShops({
        cityCode,
        merchantId,
        limit: 9999,
        offset: 0
      }).then(data => {
        let shops = (data || []).map((item, index) => {
          const distance = getDistance(this.data.lat, this.data.lng, item.latitude, item.longitude) || 0
          var distance_str = "";
          if (parseInt(distance) >= 1) {
            distance_str = distance.toFixed(1) + "km";
          } else {
            distance_str = (distance * 1000).toFixed(1) + "m";
          }
          return {
            ...item,
            distance: distance_str,
            distant: distance
          }
        }).sort((a, b) => a.distant - b.distant)
        let commonIndex = -1
        shops.forEach((item, index) => {
          if (item.shopId === this.data.selectShopId) {
            commonIndex = index
          }
        })
        if (commonIndex !== -1) {
          const split = shops.splice(commonIndex, 1)
          shops = split.concat(shops)
          this.setData({
            activeIdx: 0
          })
        } else {
          this.setData({
            activeIdx: -1
          })
        }
        if (this.data.canSelectShopIds.length) {
          this.setData({
            shops: shops.filter(item => this.data.canSelectShopIds.includes(item.shopId))
          })
        } else {
          this.setData({
            shops
          })
        }
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none'
        })
      })
    } else {
      wx.showToast({
        title: '定位失败，请重试',
        icon: 'none',
        duration: 2000
      })
    }
  },
  clickBanner() {
    wx.reportAnalytics('currency_banner')
  },
  /**
     * 获取svip会员信息
     */
  getMemberInfo: function () {
    var param = {};
    param.merchantId = wx.getStorageSync('merchantId'); //商户id
    param.shopId = this.data.shopId; //门店id
    svipModel.svipQuery(param).then(data => {
      wx.navigateTo({
        url: `/pages/svip/purchase/index?shopId=${this.data.shopId}`
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.cityCode) {
      this.setData({
        sVipType: options.sVipType || null,
        selectCity: {
          name: options.cityName,
          code: options.cityCode
        },
        selectShopId: options.shopId || '',
        from: options.from || '',
        canSelectShopIds: JSON.parse(options.canSelectShopIds || '[]')
      });
    } else {
      this.setData({
        sVipType: options.sVipType || null
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getLocation()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
